package com.xjrsoft.common.converter;

import com.xjrsoft.core.tool.utils.StringUtil;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

@Component
public class StringToLocalDateTimeConverter  implements Converter<String, LocalDateTime> {
    @Override
    public LocalDateTime convert(String value) {
        if (StringUtil.isNotBlank(value)) {
            int length = value.length();
            if ("yyyy-MM-dd".length() == length) {
                LocalDate localDate = LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                return LocalDateTime.from(localDate.atStartOfDay());
            } else if ("yyyy-MM-dd hh:mm:ss".length() == length) {
                return LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } else if ("yyyy-MM".length() == length) {
                YearMonth yearMonth = YearMonth.parse(value, DateTimeFormatter.ofPattern("yyyy-MM"));
                return LocalDateTime.from(yearMonth.atDay(1).atStartOfDay());
            } else if ("yyyy".length() == length) {
                Year year = Year.parse(value, DateTimeFormatter.ofPattern("yyyy"));
                return LocalDateTime.from(year.atDay(1).atStartOfDay());
            }
        }
        return null;
    }
}
